<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片内容区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="queryInfo.query"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userlist" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="SwitchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserByid(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配管理"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- page分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 15, 20]"
        :page-size="2"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 表单内容主体区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <!-- 编辑表单信息 -->
        <el-form
          ref="editEormRef"
          :rules="editEormRules"
          :model="editEorm"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editEorm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editEorm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editEorm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="attotDialogVisible"
        width="50%"
        @close="jianting"
      >
        <div>
          <p>当前的用户： {{ userInfo.username }}</p>
          <p>当前的角色： {{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="attotDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default ({
  data() {
    // 邮箱效验规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 手机效验规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数是第几页
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 控制添加用户的对话框显示或隐藏
      addDialogVisible: false,
      // 修改用户信息对话框显示与隐藏
      editDialogVisible: false,
      // 分配角色对话框显示与隐藏
      attotDialogVisible: false,
      // 分配角色接收数组
      userInfo: {},
      // 所有角色列表入口
      rolesList: [],
      // 已选中的ID角色值
      selectedRoleId: '',
      // 编辑修改数据
      editEorm: {},
      // 添加表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改编辑信息验证规则
      editEormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 在生命周期中调取首屏数据函数
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$notify.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res.data)
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 SwitchChange 状态改变
    async SwitchChange(userinfo) {
      // 调用API接口保存当前的状态
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)

      if (res.meta.status !== 200) {
        // 如果调用出错，最好把数据还原
        userinfo.mg_state = !userinfo.mg_state
        return this.$notify.error('res.meta.msg')
      }
      this.$notify.success(res.meta.msg)
    },
    // 重置添加用户表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      // 添加用户信息预效验
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid); 返回 true或false
        if (!valid) return
        // 通过可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$notify.error(res.meta.msg)
        }
        this.$notify.success(res.meta.msg)
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户信息
    async showEditDialog(id) {
      // 拿到id数据调用接口获取到对应信息
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$notify.error('获取数据失败！')
      }
      this.editEorm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑表单关闭重置事件
    editDialogClose() {
      this.$refs.editEormRef.resetFields()
    },
    // 表单确定预验证操作
    editUserInfo() {
      this.$refs.editEormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 如果通过，就修改相应参数
        const { data: res } = await this.$http.put('users/' + this.editEorm.id, {
          email: this.editEorm.email, mobile: this.editEorm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$notify.error('提交信息错误')
        }
        // 确定之后需要隐藏对话框
        this.editDialogVisible = false
        // 更新信息
        this.getUserList()
        // 提示操作成功
        this.$notify.success('更新信息成功')
      })
    },
    // 删除数据操作
    async removeUserByid(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值是字符串 confirm
      // 如果用户徐晓删除, 返回值是 cancel
      if (confirmResult !== 'confirm') {
        return this.$notify.info('已取消删除')
      }
      // 确定删除就调用接口执行删除操作
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$notify.error('删除用户失败')
      }
      this.$notify.success('删除用户成功')
      this.getUserList()
    },
    // 分配角色操作
    async setRole(userinfo) {
      this.userInfo = userinfo

      // 获取角色接口列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$notify.error('获取角色列表失败')
      }

      this.rolesList = res.data

      this.attotDialogVisible = true
    },
    // 点击分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$notify.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })

      if (res.meta.status !== 200) {
        return this.$notify.error('更新角色失败')
      }
      this.$notify.success('更新角色成功')
      this.attotDialogVisible = false
      this.getUserList()
    },
    // 监听角色重置选择框
    jianting() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
})
</script>

<style lang="less" scoped>
</style>
